import {  PlusOutlined } from '@ant-design/icons';
import {
  type ActionType,
  ModalForm,
  type ProColumns,
  ProFormDigit,
  ProFormGroup,
  ProTable
} from '@ant-design/pro-components';
import {Button, message, Tag} from 'antd';
import React, {useEffect, useRef, useState} from "react";
import {addTransfer, listTransferOrderVoByPage} from "@/services/transfer/api";

import {
  ProForm,
  ProFormText,
  ProFormList,
} from '@ant-design/pro-components';

type TransferFormProps = {
  open: boolean;
  onCancel: () => void;
}

const TransferForm: React.FC<TransferFormProps> = (props) => {
  const handleCreate = async (values: TransferDTO) => {
    const res = await addTransfer(values);
    if (res.code !== 0 || res.data !== true) {
      message.error("调拨单创建失败" + res.message);
      return;
    }
    message.success("调拨单创建成功");
    props.onCancel();
  }

  return (
    <ModalForm<TransferDTO>
      layout="vertical"
      open={props.open}
      onFinish={async (values) => {
        await handleCreate(values);
      }}
      submitter={{
        render: (_, dom) => <div style={{ textAlign: 'center' }}>{dom}</div>,
      }}
      modalProps={
        {
          destroyOnClose: true,
          onCancel: props.onCancel,
        }
      }
    >
      {/* 主单信息 */}
      <ProForm.Group>
        <ProFormText
          name="stockTransferNo"
          label="调拨单号"
          width="md"
          rules={[{ required: true, message: '请输入调拨单号' }]}
        />
        <ProFormText
          name="originWarehouseCode"
          label="源仓库编码"
          width="md"
          rules={[{ required: true, message: '请输入源仓库编码' }]}
        />
        <ProFormText
          name="targetWarehouseCode"
          label="目标仓库编码"
          width="md"
          rules={[{ required: true, message: '请输入目标仓库编码' }]}
        />
      </ProForm.Group>

      {/* 动态子单列表 */}
      <ProFormList
        name="transferDetails"
        creatorButtonProps={{
          creatorButtonText: '添加调拨明细',
          style: { width: '200px' },
        }}
        itemRender={({ listDom, action }, { index }) => (
          <div
            style={{
              position: 'relative',
              padding: 24,
              border: '1px solid #eee',
              marginBottom: 24,
            }}
          >
            {listDom}
            <div style={{ position: 'absolute', top: 8, right: 8 }}>
              {action}
            </div>
          </div>
        )}
      >
        <ProFormGroup>
          <ProFormText name='stockTransferDetailNo' label='调拨子单号' required={true} />
          <ProFormText name='goodsNo' label='货品编码' required={true} />
          <ProFormText name='goodsName' label='货品名称'/>
          <ProFormDigit name='num' label='数量' required={true} initialValue={0}/>
        </ProFormGroup>
      </ProFormList>
    </ModalForm>
  );
};

const TransferAdd: React.FC = () => {
  const columns: ProColumns<TransferOrderVo>[] = [
    {
      title: '源仓库名称',
      width: 120,
      dataIndex: 'originWarehouseName',
    },
    {
      title: '目标仓库名称',
      width: 120,
      dataIndex: 'targetWarehouseName',
    },
    {
      title: '调拨单号',
      width: 120,
      dataIndex: 'transferNo',
    },
    {
      title: '状态',
      width: 120,
      hideInSearch: true,
      render: (text, record) => {
        if (record.status===90) {
          return <Tag color="#2db7f5">完成</Tag>;
        } else {
          return <Tag color="yellow">作业中</Tag>;
        }
      },
      dataIndex: 'status',
    },
    {
      title: '创建时间',
      width: 120,
      hideInSearch: true,
      dataIndex: 'createTime',
    }
  ];

  const actionRef = useRef<ActionType>();
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [isCreate, setIsCreate] = useState<boolean>(false);
  const [data, setData] = useState<TransferOrderVo[]>([]);
  const [total, setTotal] = useState<number>(0);

  const loadData = async (params: any) => {
    const res = await listTransferOrderVoByPage({
      params: params,
      pageNum: currentPage,
      pageSize: 10,
    });
    if (res.code !== 0) {
      message.error("调拨单数据加载失败 " + res.message);
      return;
    }
    setData(res?.data?.records || []);
    setTotal(res?.data?.total || 0);
  }

  useEffect(() => {
    loadData({});
  }, [currentPage]);

  return (
    <>
      <ProTable<TransferOrderVo>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        dataSource={data}
        request={async (params) => {
          await loadData(params);
          return data;
        }}
        editable={{
          type: 'multiple',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 10,
          onChange: (page) => setCurrentPage(page),
          total: total,
        }}
        headerTitle="调拨单"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setIsCreate(true);
            }}
            type="primary"
          >
            调拨单创建
          </Button>,
        ]}
      />
      <TransferForm
        onCancel={() => setIsCreate(false)}
        open={isCreate}
      />
    </>
  )
}

export default TransferAdd;
